package com.itgungnir.diyshuo.activity.main_activity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.RadioGroup;

import com.itgungnir.diyshuo.activity.R;
import com.itgungnir.diyshuo.base.BaseActivity;

public class MainActivity extends BaseActivity implements MainContract.View {
    private RadioGroup tabBar;

    private MainPresenter presenter = new MainPresenter(this);
    private long exitTime = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        initEvents();
    }

    /**
     * 初始化布局界面
     */
    private void initViews() {
        tabBar = (RadioGroup) findViewById(R.id.find_main_tabbar);
        initFragments();
    }

    /**
     * 初始化事件
     */
    private void initEvents() {
        // 当切换RadioGroup中的Item时触发的事件
        tabBar.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                changeFragment(checkedId);
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initFragments() {
        presenter.initFragments(MainActivity.this);
    }

    @Override
    public void changeFragment(int checkedId) {
        presenter.changeFragment(MainActivity.this, checkedId);
    }

    /**
     * 点击两次退出程序
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                this.exitApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 退出程序
     */
    private void exitApp() {
        // 判断2次点击事件时间
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            popToast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }
}